/**
 * create by young (young2f@outlook.com) on 2020/9/16
 * 选择辅料
 */


'use strict';
import React from 'react';
import {Button, Col, DatePicker, Form, Icon, Input, Modal, notification, Row, Switch, Upload} from 'antd';

import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';

import {FormField, FormLayout, ModalFooter} from "antd-extra";
import notify from "../../../components/NotificationExtra";
import ViewTitle from "../../../components/ViewTitle";

moment.locale('zh-cn');

@Form.create()
@connect(({
            user,
            global,
            dynamicLabel,
            material,
            store
          }) => ({...user, ...material, ...dynamicLabel, ...global, ...store}))
export default class ModalCreateInboundLot extends FormBase {
  constructor(props) {
    super(props);
    this.state = {fileList: []};
  }

  componentDidMount() {

  }

  renderFoot = () => {
    const {foot, value, modalRef, form, callback,values} = this.props;

    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            const {modalRef} = this.props;
            form.validateFields((err, _values) => {
              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  console.log(item);
                  notification.error(item);
                });
                return;
              }

              const {spec, type, subcategory, number} = this.props.values;
              const {fileList} = this.state;
              _values.fileList = fileList;

              const {chkSpec, chkType, chkNumber, chkCount} = _values;
              _values.checkInfo = {chkSpec, chkType, chkNumber, chkCount};
              _.merge(_values, {spec, type, subcategory, number});
              _.merge(values, _values);
              callback(values);
              modalRef.close();
            });
          }}>确定</Button>

          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };

  checkProcureOrderInfo() {
    const {form, cols = 1, values = {}} = this.props;
    console.log('valuess', values);
    const {spec, type, number, count} = values;

    return <FormLayout form={form} cols={cols}>
      <FormField
        label={`确认物料规格：${spec}`}
        name={'chkSpec'}
      >
        <Switch checkedChildren="是" unCheckedChildren="否"></Switch>
      </FormField>
      <FormField
        label={`确认物料类型：${type}`}
        name={'chkType'}
      >
        <Switch checkedChildren="是" unCheckedChildren="否"></Switch>
      </FormField>
      <FormField
        label={`确认物料编号：${number}`}
        name={'chkNumber'}
      >
        <Switch checkedChildren="是" unCheckedChildren="否"></Switch>
      </FormField>
      <FormField
        label={`确认采购数量：${count}`}
        name={'chkCount'}
      >
        <Switch checkedChildren="是" unCheckedChildren="否"></Switch>
      </FormField>

    </FormLayout>;
  }

  inboundInfo() {
    const {form, cols = 2} = this.props;
    return <FormLayout form={form} cols={cols}>

      <FormField
        label={'入库数量'}
        name={'inboundCount'}
        required={true}
      >
        <Input style={{width: '100%'}}></Input>
      </FormField>
      <FormField
        label={'入库时间'}
        name={'inboundDate'}
        required={true}
        initialValue={moment()}
      >
        <DatePicker style={{width: '100%'}}></DatePicker>
      </FormField>
    </FormLayout>;
  }

  handleCancel = () => this.setState({previewVisible: false});

  handlePreview = async file => {

    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true
    });
  };
  handleChange = ({fileList}) => {

    _.map(fileList, async file => {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
    });
    this.setState({fileList});
  };


  render() {
    const {style} = this.props;
    const {previewVisible, previewImage, fileList} = this.state;
    const uploadButton = (
      <div>
        <Icon type="plus"/>
        <div className="ant-upload-text">上传图片</div>
      </div>
    );
    return (
      <div style={{...style}}>
        <ViewTitle
          title={'确认采购信息'}
        ></ViewTitle>
        {this.checkProcureOrderInfo()}
        <ViewTitle
          title={'录入入库信息'}
        ></ViewTitle>
        {this.inboundInfo()}
        <ViewTitle
          title={'上传入库单'}
        ></ViewTitle>
        {
          <div style={{marginLeft: '64px'}}>
            <Upload
              action={'http://127.0.0.1:28900/api/global/upload?type=inboundLot'} // 替换为你的上传API地址
              listType="picture-card"
              fileList={fileList}
              onPreview={this.handlePreview}
              onChange={this.handleChange}
              beforeUpload={(file, fileList) => {
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                  notify({type: 'error', message: '文件过大！'});
                  return isLt2M;
                }

                return false;
              }}
            >
              {uploadButton}
            </Upload>
            <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
              <img alt="example" style={{width: '100%'}} src={previewImage}/>
            </Modal>
          </div>
        }
        {this.renderFoot()}
      </div>

    );
  }
}

function getBase64(file) {
  console.log('getBase64', file);
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
